package com.atguigu.daijia.map.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.map.service.MapService;
import com.atguigu.daijia.model.form.map.CalculateDrivingLineForm;
import com.atguigu.daijia.model.vo.map.DrivingLineVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class MapServiceImpl implements MapService {

    @Autowired
    private RestTemplate restTemplate;


    @Value("${tencent.map.key}")//读取配置文件
    private String key;

    //根据起始点经纬度 返回路线的距离，时间，路线方案
    @Override
    public DrivingLineVo calculateDrivingLine(CalculateDrivingLineForm lineForm) {
        //请求腾讯提供接口，按照接口要求传递相关参数，返回需要结果
        //使用HttpClient，目前Spring封装调用工具使用RestTemplate
        //定义调用腾讯地址
        String url="https://apis.map.qq.com/ws/direction/v1/driving/?from={from}&to={to}&key={key}";
        //请求参数
        HashMap<String, String> map = new HashMap<>();
        //开始位置（经度+，+纬度）
        map.put("from",lineForm.getStartPointLatitude()+","+lineForm.getStartPointLongitude());
        //结束位置
        map.put("to",lineForm.getEndPointLatitude()+","+lineForm.getEndPointLongitude());
        //位置服务的key
        map.put("key", key);
        //发起请求 TODO  restTemplate的用法
        JSONObject jsonObject = restTemplate.getForObject(url, JSONObject.class, map);
        int status = jsonObject.getIntValue("status");
        //失败
        if (status!=0){
            throw new GuiguException(ResultCodeEnum.MAP_FAIL);
        }
        //获取路线的第一条
        JSONObject route = jsonObject.getJSONObject("result").getJSONArray("routes").getJSONObject(0);
        BigDecimal duration = route.getBigDecimal("duration");//预估时间
        BigDecimal distance = route.getBigDecimal("distance");//预估距离
        //换为千米
        distance = distance.divide(new BigDecimal(1000)).setScale(2, RoundingMode.HALF_UP);
        //获得路线
        JSONArray polyline = route.getJSONArray("polyline");

        //封装返回值
        DrivingLineVo drivingLineVo = new DrivingLineVo();
        drivingLineVo.setDistance(distance);//路线的距离
        drivingLineVo.setDuration(duration);//该路线下的预估距离
        drivingLineVo.setPolyline(polyline);//方案路线坐标点串
        return drivingLineVo;
    }

}
